#include "util/sk_utf8_buffer.h"
void UTF8Buffer_construct(UTF8Buffer * o,SK_BYTE *buf,SK_INT32 len)
{
	o->m_buf = buf;
	o->m_len = len;
	o->m_curPos = 0;
}


void UTF8Buffer_destruct(UTF8Buffer * o)
{
	o->m_buf = SK_NULL;
	o->m_len = 0;
	o->m_curPos = 0;

}
SK_INT32 UTF8Buffer_readChar(UTF8Buffer * o)
{
	SK_WCHAR uChar;
	SK_INT32 pos = o->m_curPos;
	if(pos < o->m_len)
	{
		// get the begining char
		if ((o->m_buf[pos] & 0x80) == 0)
		{
			uChar = o->m_buf[pos];
			o->m_curPos += 1;
		}
		else if ((o->m_buf[pos] & 0xE0) == 0xC0)
		{
			// < 110x-xxxx 10xx-xxxx
			uChar  = (o->m_buf[pos] & 0x1F) << 6;
			uChar |= (o->m_buf[pos + 1] & 0x3F);
			o->m_curPos += 2;
		} 
		else if ((o->m_buf[pos] & 0xF0) == 0xE0)
		{
			uChar  = (o->m_buf[pos] & 0x0F) << 12;
			uChar |= (o->m_buf[pos + 1] & 0x3F) << 6;
			uChar |= (o->m_buf[pos + 2] & 0x3F);
			o->m_curPos += 3;
		} 
		else if ((o->m_buf[pos] & 0xF8) == 0xF0)
		{
			// < 1111-0xxx 10xx-xxxx 10xx-xxxx 10xx-xxxx
			uChar  = (o->m_buf[pos] & 0x07) << 18;
			uChar |= (o->m_buf[pos + 1] & 0x3F) << 12;
			uChar |= (o->m_buf[pos + 2] & 0x3F) << 6;
			uChar |= (o->m_buf[pos + 3] & 0x3F);
			o->m_curPos += 4;
		} 
		else if ((o->m_buf[pos] & 0xfc) == 0xf8)
		{
			// 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
			uChar = (o->m_buf[pos] & 0x03) << 24;
			uChar |= (o->m_buf[pos + 1] & 0x3F) << 18;
			uChar |= (o->m_buf[pos + 2] & 0x3F) << 12;
			uChar |= (o->m_buf[pos + 3] & 0x3F) << 6;
			uChar |= (o->m_buf[pos + 4] & 0x3F);
			o->m_curPos += 5;
		} 
		else if((o->m_buf[pos] & 0xfe) == 0xfc)
		{
			//1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx  
			uChar = (o->m_buf[pos] & 0x01) << 30;
			uChar |= (o->m_buf[pos + 1] & 0x3F) << 24;
			uChar |= (o->m_buf[pos + 2] & 0x3F) << 18;
			uChar |= (o->m_buf[pos + 3] & 0x3F) << 12;
			uChar |= (o->m_buf[pos + 4] & 0x3F) << 6;
			uChar |= (o->m_buf[pos + 5] & 0x3F);
			o->m_curPos += 6;
		}
		else
		{
			//bad utf8 char
			uChar = o->m_buf[pos];
			o->m_curPos += 1;
		}
		return uChar;
	}
	else
	{
		return -1;
	}
}

